
from storage_mysql import TodoStorageWithMysql
from flask import Flask, request
app = Flask(__name__)

app.config['JSON_AS_ASCII'] = False

storage = TodoStorageWithMysql()


@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"


@app.route("/todos", methods=['GET'])
def list_todos():
    return {"todos": [x.__dict__ for x in storage.get_list()]}

@app.route("/create", methods=['POST'])
def create():

    if 'title' not in request.form:
        return '参数错误，必须提供 title 参数', 400
    todo = storage.create(request.form['title'])
    return todo.__dict__


@app.route("/mark_completed", methods=['GET'])
def mark_completed():

    if 'id' not in request.args:
        return '参数错误，必须提供 id 参数', 400
    else:
        return {"todos": [x.__dict__ for x in storage.mark_completed(int(request.args["id"]))]}

@app.route("/delete", methods=['POST'])
def delete():
    if "id" not in request.form:
        return '参数错误，必须提供 title 参数', 400
    else:
        return {"todos":[x.__dict__ for x in storage.delete(int(request.form["id"]))]}

@app.route("/things",methods=['GET'])
def things():
    if request.args.get('completed')=='1':
        return {"todos":[x.__dict__ for x in storage.over_completed()]}
    elif request.args.get('completed')=='all':
        return {"todos":[x.__dict__ for x in storage.get_list()]}
    else:
        return {"todos": [x.__dict__ for x in storage.never_finished()]}
if __name__ == '__main__':
    app.run()
